<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>致筑网 - 应用商店管理后台</title>
    <!-- 引入外部资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入图表库用于数据统计 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>

    <!-- 配置Tailwind主题 - 保持与前台一致的公司风格 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#0a3d62',      // 工程深蓝（主色调）
                        secondary: '#3c6382',    // 工程浅蓝（辅助色）
                        accent: '#60a3bc',       // 工程亮蓝（强调色）
                        success: '#27ae60',      // 成功色
                        warning: '#f39c12',      // 警告色
                        danger: '#e74c3c',       // 危险色
                        neutral: {
                            100: '#f5f6fa',     // 最浅背景色
                            200: '#dcdde1',     // 边框和分割线
                            300: '#b2bec3',     // 次要文本和图标
                            600: '#636e72',     // 中等重要文本
                            700: '#2d3436',     // 主要文本
                            800: '#1e272e',     // 标题文本
                            900: '#192a56',     // 深色背景
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .sidebar-item-active {
                @apply bg-primary/10 text-primary border-l-4 border-primary;
            }
            .card-shadow {
                @apply shadow-sm hover:shadow-md transition-shadow;
            }
            .btn-action {
                @apply px-3 py-1.5 rounded text-sm font-medium transition-colors;
            }
            .btn-primary {
                @apply btn-action bg-primary text-white hover:bg-primary/90;
            }
            .btn-secondary {
                @apply btn-action bg-white border border-neutral-200 text-neutral-700 hover:bg-neutral-50;
            }
            .btn-danger {
                @apply btn-action bg-danger text-white hover:bg-danger/90;
            }
            .form-input {
                @apply w-full px-3 py-2 border border-neutral-200 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all;
            }
            .scrollbar-thin {
                scrollbar-width: thin;
                scrollbar-color: theme('colors.neutral.300') transparent;
            }
            .scrollbar-thin::-webkit-scrollbar {
                width: 5px;
                height: 5px;
            }
            .scrollbar-thin::-webkit-scrollbar-thumb {
                @apply bg-neutral-300 rounded-full hover:bg-neutral-400 transition-colors;
            }
        }
    </style>
</head>
<body class="bg-neutral-100 font-sans text-neutral-700 min-h-screen flex flex-col overflow-hidden">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm sticky top-0 z-30">
    <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16">
            <!-- 左侧：Logo和名称 -->
            <div class="flex items-center">
                <!-- 移动端菜单按钮 -->
                <button id="mobile-menu-button" class="md:hidden p-2 mr-2 rounded-md text-neutral-600 hover:text-primary hover:bg-neutral-100 transition-colors">
                    <i class="fa fa-bars text-xl"></i>
                </button>

                <!-- 公司Logo和名称 -->
                <div class="flex items-center">
                    <i class="fa fa-cubes text-2xl text-primary mr-3"></i>
                    <span class="text-xl font-bold text-neutral-800">致筑网</span>
                    <span class="hidden md:inline-block ml-2 text-sm text-neutral-600">应用商店管理后台</span>
                </div>
            </div>

            <!-- 右侧：用户相关功能 -->
            <div class="flex items-center space-x-4">
                <!-- 通知中心 -->
                <div class="relative">
                    <button id="notification-button" class="p-2 rounded-full hover:bg-neutral-100 transition-colors relative">
                        <i class="fa fa-bell text-neutral-600"></i>
                        <!-- 通知数量提示 -->
                        <span class="absolute -top-1 -right-1 w-5 h-5 bg-danger text-white text-xs rounded-full flex items-center justify-center" id="notification-count">2</span>
                    </button>
                </div>

                <!-- 帮助中心 -->
                <button class="p-2 rounded-full hover:bg-neutral-100 transition-colors">
                    <i class="fa fa-question-circle text-neutral-600"></i>
                </button>

                <!-- 用户头像和下拉菜单 -->
                <div class="relative" id="user-menu-container">
                    <button id="user-menu-button" class="flex items-center space-x-2 focus:outline-none">
                        <img src="https://picsum.photos/id/1005/200/200" alt="管理员头像" class="w-8 h-8 rounded-full object-cover border-2 border-white shadow-sm">
                        <span class="hidden md:inline-block text-sm font-medium" id="admin-name">管理员</span>
                        <i class="fa fa-chevron-down text-xs text-neutral-500 hidden md:block"></i>
                    </button>

                    <!-- 用户下拉菜单 - 默认隐藏 -->
                    <div id="user-dropdown-menu" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-1 z-50 border border-neutral-200">
                        <a href="#" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                            <i class="fa fa-user-circle mr-2"></i>个人资料
                        </a>
                        <a href="#" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                            <i class="fa fa-cog mr-2"></i>系统设置
                        </a>
                        <div class="border-t border-neutral-200 my-1"></div>
                        <a href="#" id="logout-button" class="block px-4 py-2 text-sm text-danger hover:bg-neutral-100">
                            <i class="fa fa-sign-out mr-2"></i>退出登录
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- 主要内容区 -->
<main class="flex-1 flex overflow-hidden">
    <!-- 侧边栏导航 - 管理功能菜单 -->
    <aside id="sidebar" class="w-64 bg-white shadow-sm border-r border-neutral-200 flex-shrink-0 hidden md:block overflow-y-auto scrollbar-thin">
        <nav class="p-4">
            <!-- 仪表盘 -->
            <div class="mb-6">
                <h3 class="text-xs font-semibold text-neutral-500 uppercase tracking-wider mb-3">控制台</h3>
                <ul class="space-y-1">
                    <li>
                        <a href="#dashboard" class="sidebar-item-active flex items-center px-3 py-2 text-sm rounded-md">
                            <i class="fa fa-dashboard w-6 text-center mr-3"></i>
                            <span>数据概览</span>
                        </a>
                    </li>
                </ul>
            </div>

            <!-- 应用管理 -->
            <div class="mb-6">
                <h3 class="text-xs font-semibold text-neutral-500 uppercase tracking-wider mb-3">应用管理</h3>
                <ul class="space-y-1">
                    <li>
                        <a href="#app-list" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-th-large w-6 text-center mr-3"></i>
                            <span>应用列表</span>
                        </a>
                    </li>
                    <li>
                        <a href="#app-review" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-check-square-o w-6 text-center mr-3"></i>
                            <span>应用审核</span>
                            <span class="ml-auto bg-warning text-white text-xs px-2 py-0.5 rounded-full">5</span>
                        </a>
                    </li>
                    <li>
                        <a href="#app-categories" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-folder w-6 text-center mr-3"></i>
                            <span>分类管理</span>
                        </a>
                    </li>
                </ul>
            </div>

            <!-- 用户管理 -->
            <div class="mb-6">
                <h3 class="text-xs font-semibold text-neutral-500 uppercase tracking-wider mb-3">用户管理</h3>
                <ul class="space-y-1">
                    <li>
                        <a href="#user-list" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-users w-6 text-center mr-3"></i>
                            <span>用户列表</span>
                        </a>
                    </li>
                    <li>
                        <a href="/temp/role_management" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-key w-6 text-center mr-3"></i>
                            <span>角色权限</span>
                        </a>
                    </li>
                </ul>
            </div>

            <!-- 系统设置 -->
            <div>
                <h3 class="text-xs font-semibold text-neutral-500 uppercase tracking-wider mb-3">系统设置</h3>
                <ul class="space-y-1">
                    <li>
                        <a href="#system-settings" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-cogs w-6 text-center mr-3"></i>
                            <span>基本设置</span>
                        </a>
                    </li>
                    <li>
                        <a href="#operation-log" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-history w-6 text-center mr-3"></i>
                            <span>操作日志</span>
                        </a>
                    </li>
                </ul>
            </div>
        </nav>
    </aside>

    <!-- 主内容区域 -->
    <div class="flex-1 overflow-y-auto scrollbar-thin p-4 md:p-6 bg-neutral-50">
        <!-- 页面标题和操作区 -->
        <div class="mb-6 flex flex-col md:flex-row md:items-center justify-between">
            <div>
                <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-neutral-800">数据概览</h1>
                <p class="text-neutral-600 mt-1">
                    <span id="current-date"></span> |
                    <span>总应用数: <span id="total-apps">24</span></span> |
                    <span>总用户数: <span id="total-users">1,256</span></span>
                </p>
            </div>
            <div class="mt-4 md:mt-0 flex space-x-3">
                <div class="relative">
                    <select class="form-input pr-8 py-1.5 w-full md:w-auto">
                        <option>最近7天</option>
                        <option>最近30天</option>
                        <option>最近90天</option>
                        <option>今年</option>
                        <option>自定义</option>
                    </select>
                    <i class="fa fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400 pointer-events-none"></i>
                </div>
                <button class="btn-primary">
                    <i class="fa fa-download mr-2"></i>
                    <span>导出数据</span>
                </button>
            </div>
        </div>

        <!-- 数据统计卡片 -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-xl p-5 shadow-sm card-shadow">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-neutral-500 text-sm">总下载量</p>
                        <h3 class="text-2xl font-bold text-neutral-800 mt-1" id="total-downloads">15,824</h3>
                        <p class="text-success text-xs mt-2 flex items-center">
                            <i class="fa fa-arrow-up mr-1"></i>
                            <span>较上月增长 12.5%</span>
                        </p>
                    </div>
                    <div class="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center">
                        <i class="fa fa-download text-primary text-xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl p-5 shadow-sm card-shadow">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-neutral-500 text-sm">活跃用户</p>
                        <h3 class="text-2xl font-bold text-neutral-800 mt-1" id="active-users">846</h3>
                        <p class="text-success text-xs mt-2 flex items-center">
                            <i class="fa fa-arrow-up mr-1"></i>
                            <span>较上月增长 8.2%</span>
                        </p>
                    </div>
                    <div class="w-12 h-12 rounded-lg bg-accent/10 flex items-center justify-center">
                        <i class="fa fa-users text-accent text-xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl p-5 shadow-sm card-shadow">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-neutral-500 text-sm">待审核应用</p>
                        <h3 class="text-2xl font-bold text-neutral-800 mt-1" id="pending-apps">5</h3>
                        <p class="text-danger text-xs mt-2 flex items-center">
                            <i class="fa fa-exclamation-circle mr-1"></i>
                            <span>需要及时处理</span>
                        </p>
                    </div>
                    <div class="w-12 h-12 rounded-lg bg-warning/10 flex items-center justify-center">
                        <i class="fa fa-clock-o text-warning text-xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl p-5 shadow-sm card-shadow">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-neutral-500 text-sm">今日新增用户</p>
                        <h3 class="text-2xl font-bold text-neutral-800 mt-1" id="new-users-today">32</h3>
                        <p class="text-danger text-xs mt-2 flex items-center">
                            <i class="fa fa-arrow-down mr-1"></i>
                            <span>较昨日下降 3.1%</span>
                        </p>
                    </div>
                    <div class="w-12 h-12 rounded-lg bg-success/10 flex items-center justify-center">
                        <i class="fa fa-user-plus text-success text-xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表统计区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
            <!-- 下载趋势图表 -->
            <div class="bg-white rounded-xl p-5 shadow-sm card-shadow lg:col-span-2">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="font-semibold text-neutral-800">下载量趋势</h3>
                    <div class="flex space-x-2">
                        <button class="px-2 py-1 text-xs bg-primary/10 text-primary rounded">日</button>
                        <button class="px-2 py-1 text-xs bg-neutral-100 text-neutral-600 rounded hover:bg-neutral-200">周</button>
                        <button class="px-2 py-1 text-xs bg-neutral-100 text-neutral-600 rounded hover:bg-neutral-200">月</button>
                    </div>
                </div>
                <div class="h-64">
                    <canvas id="downloads-chart"></canvas>
                </div>
            </div>

            <!-- 应用分类占比 -->
            <div class="bg-white rounded-xl p-5 shadow-sm card-shadow">
                <h3 class="font-semibold text-neutral-800 mb-4">应用分类占比</h3>
                <div class="h-64">
                    <canvas id="categories-chart"></canvas>
                </div>
                <div class="grid grid-cols-2 gap-2 mt-4">
                    <div class="flex items-center">
                        <span class="w-3 h-3 rounded-full bg-primary mr-2"></span>
                        <span class="text-xs text-neutral-600">项目管理 (32%)</span>
                    </div>
                    <div class="flex items-center">
                        <span class="w-3 h-3 rounded-full bg-accent mr-2"></span>
                        <span class="text-xs text-neutral-600">设计工具 (24%)</span>
                    </div>
                    <div class="flex items-center">
                        <span class="w-3 h-3 rounded-full bg-success mr-2"></span>
                        <span class="text-xs text-neutral-600">造价算量 (18%)</span>
                    </div>
                    <div class="flex items-center">
                        <span class="w-3 h-3 rounded-full bg-warning mr-2"></span>
                        <span class="text-xs text-neutral-600">安全管理 (15%)</span>
                    </div>
                    <div class="flex items-center">
                        <span class="w-3 h-3 rounded-full bg-danger mr-2"></span>
                        <span class="text-xs text-neutral-600">文档管理 (11%)</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 最近应用列表 -->
        <div class="bg-white rounded-xl shadow-sm card-shadow mb-6">
            <div class="p-5 border-b border-neutral-200 flex justify-between items-center">
                <h3 class="font-semibold text-neutral-800">最近添加的应用</h3>
                <a href="#app-list" class="text-sm text-primary hover:underline">查看全部</a>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-neutral-200">
                    <thead class="bg-neutral-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">应用名称</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">分类</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">开发者</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">状态</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">添加时间</th>
                        <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-neutral-500 uppercase tracking-wider">操作</th>
                    </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-neutral-200">
                    <!-- 应用1 -->
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="h-10 w-10 flex-shrink-0">
                                    <img class="h-10 w-10 rounded-md object-cover" src="https://picsum.photos/id/1012/100/100" alt="智能算量工具">
                                </div>
                                <div class="ml-4">
                                    <div class="text-sm font-medium text-neutral-800">智能算量工具</div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">造价算量</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">技术部-李工</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-success/10 text-success">已上架</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-neutral-600">
                            2024-06-14
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button class="text-primary hover:text-primary/80 mr-3 app-edit-btn" data-app-id="app-101">编辑</button>
                            <button class="text-neutral-600 hover:text-neutral-900 mr-3">查看</button>
                            <button class="text-danger hover:text-danger/80 app-delete-btn" data-app-id="app-101">下架</button>
                        </td>
                    </tr>
                    <!-- 应用2 -->
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="h-10 w-10 flex-shrink-0">
                                    <img class="h-10 w-10 rounded-md object-cover" src="https://picsum.photos/id/1013/100/100" alt="材料管理系统">
                                </div>
                                <div class="ml-4">
                                    <div class="text-sm font-medium text-neutral-800">材料管理系统</div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">资源管理</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">开发组-Bob</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-success/10 text-success">已上架</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-neutral-600">
                            2024-06-12
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button class="text-primary hover:text-primary/80 mr-3 app-edit-btn" data-app-id="app-102">编辑</button>
                            <button class="text-neutral-600 hover:text-neutral-900 mr-3">查看</button>
                            <button class="text-danger hover:text-danger/80 app-delete-btn" data-app-id="app-102">下架</button>
                        </td>
                    </tr>
                    <!-- 应用3 -->
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="h-10 w-10 flex-shrink-0">
                                    <img class="h-10 w-10 rounded-md object-cover" src="https://picsum.photos/id/1014/100/100" alt="质量验收APP">
                                </div>
                                <div class="ml-4">
                                    <div class="text-sm font-medium text-neutral-800">质量验收APP</div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">质量管理</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">测试组-王工</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-warning/10 text-warning">审核中</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-neutral-600">
                            2024-06-10
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button class="text-primary hover:text-primary/80 mr-3 app-edit-btn" data-app-id="app-103">编辑</button>
                            <button class="text-neutral-600 hover:text-neutral-900 mr-3">查看</button>
                            <button class="text-danger hover:text-danger/80 app-delete-btn" data-app-id="app-103">删除</button>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
            <div class="px-6 py-3 bg-neutral-50 flex items-center justify-between border-t border-neutral-200">
                <div class="flex-1 flex justify-between sm:hidden">
                    <button class="btn-secondary">上一页</button>
                    <button class="btn-secondary ml-3">下一页</button>
                </div>
                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                        <p class="text-sm text-neutral-600">
                            显示第 <span class="font-medium">1</span> 至 <span class="font-medium">3</span> 条，共 <span class="font-medium">24</span> 条记录
                        </p>
                    </div>
                    <div>
                        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                            <button class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-neutral-200 bg-white text-sm font-medium text-neutral-500 hover:bg-neutral-50">
                                <span class="sr-only">上一页</span>
                                <i class="fa fa-chevron-left text-xs"></i>
                            </button>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-primary text-sm font-medium text-white">
                                1
                            </button>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700 hover:bg-neutral-50">
                                2
                            </button>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700 hover:bg-neutral-50">
                                3
                            </button>
                            <span class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700">
                                    ...
                                </span>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700 hover:bg-neutral-50">
                                8
                            </button>
                            <button class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-neutral-200 bg-white text-sm font-medium text-neutral-500 hover:bg-neutral-50">
                                <span class="sr-only">下一页</span>
                                <i class="fa fa-chevron-right text-xs"></i>
                            </button>
                        </nav>
                    </div>
                </div>
            </div>
        </div>

        <!-- 最近用户列表 -->
        <div class="bg-white rounded-xl shadow-sm card-shadow">
            <div class="p-5 border-b border-neutral-200 flex justify-between items-center">
                <h3 class="font-semibold text-neutral-800">最近注册用户</h3>
                <a href="#user-list" class="text-sm text-primary hover:underline">查看全部</a>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-neutral-200">
                    <thead class="bg-neutral-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">用户名</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">部门</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">角色</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">注册时间</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">状态</th>
                        <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-neutral-500 uppercase tracking-wider">操作</th>
                    </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-neutral-200">
                    <!-- 用户1 -->
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="h-10 w-10 flex-shrink-0">
                                    <img class="h-10 w-10 rounded-full object-cover" src="https://picsum.photos/id/1027/100/100" alt="陈工程师">
                                </div>
                                <div class="ml-4">
                                    <div class="text-sm font-medium text-neutral-800">陈工程师</div>
                                    <div class="text-xs text-neutral-500">chen@example.com</div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">结构设计部</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">普通用户</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-neutral-600">
                            2024-06-15 09:24
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-success/10 text-success">活跃</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button class="text-primary hover:text-primary/80 mr-3 user-edit-btn" data-user-id="user-201">编辑</button>
                            <button class="text-neutral-600 hover:text-neutral-900 mr-3">详情</button>
                            <button class="text-danger hover:text-danger/80 user-block-btn" data-user-id="user-201">禁用</button>
                        </td>
                    </tr>
                    <!-- 用户2 -->
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="h-10 w-10 flex-shrink-0">
                                    <img class="h-10 w-10 rounded-full object-cover" src="https://picsum.photos/id/1025/100/100" alt="林工">
                                </div>
                                <div class="ml-4">
                                    <div class="text-sm font-medium text-neutral-800">林工</div>
                                    <div class="text-xs text-neutral-500">lin@example.com</div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">项目部</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">普通用户</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-neutral-600">
                            2024-06-14 15:42
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-success/10 text-success">活跃</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button class="text-primary hover:text-primary/80 mr-3 user-edit-btn" data-user-id="user-202">编辑</button>
                            <button class="text-neutral-600 hover:text-neutral-900 mr-3">详情</button>
                            <button class="text-danger hover:text-danger/80 user-block-btn" data-user-id="user-202">禁用</button>
                        </td>
                    </tr>
                    <!-- 用户3 -->
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="h-10 w-10 flex-shrink-0">
                                    <img class="h-10 w-10 rounded-full object-cover" src="https://picsum.photos/id/1066/100/100" alt="赵经理">
                                </div>
                                <div class="ml-4">
                                    <div class="text-sm font-medium text-neutral-800">赵经理</div>
                                    <div class="text-xs text-neutral-500">zhao@example.com</div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">工程部</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-neutral-600">管理员</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-neutral-600">
                            2024-06-13 11:05
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-success/10 text-success">活跃</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button class="text-primary hover:text-primary/80 mr-3 user-edit-btn" data-user-id="user-203">编辑</button>
                            <button class="text-neutral-600 hover:text-neutral-900 mr-3">详情</button>
                            <button class="text-neutral-400 cursor-not-allowed">禁用</button>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
            <div class="px-6 py-3 bg-neutral-50 flex items-center justify-between border-t border-neutral-200">
                <div class="flex-1 flex justify-between sm:hidden">
                    <button class="btn-secondary">上一页</button>
                    <button class="btn-secondary ml-3">下一页</button>
                </div>
                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                        <p class="text-sm text-neutral-600">
                            显示第 <span class="font-medium">1</span> 至 <span class="font-medium">3</span> 条，共 <span class="font-medium">1,256</span> 条记录
                        </p>
                    </div>
                    <div>
                        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                            <button class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-neutral-200 bg-white text-sm font-medium text-neutral-500 hover:bg-neutral-50">
                                <span class="sr-only">上一页</span>
                                <i class="fa fa-chevron-left text-xs"></i>
                            </button>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-primary text-sm font-medium text-white">
                                1
                            </button>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700 hover:bg-neutral-50">
                                2
                            </button>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700 hover:bg-neutral-50">
                                3
                            </button>
                            <span class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700">
                                    ...
                                </span>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700 hover:bg-neutral-50">
                                42
                            </button>
                            <button class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-neutral-200 bg-white text-sm font-medium text-neutral-500 hover:bg-neutral-50">
                                <span class="sr-only">下一页</span>
                                <i class="fa fa-chevron-right text-xs"></i>
                            </button>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- 添加/编辑应用的模态框 - 默认隐藏 -->
<div id="app-modal" class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center">
    <div class="bg-white rounded-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="p-5 border-b border-neutral-200 flex justify-between items-center">
            <h3 class="text-lg font-semibold text-neutral-800" id="app-modal-title">添加新应用</h3>
            <button id="close-app-modal" class="text-neutral-500 hover:text-neutral-700">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="p-5">
            <form id="app-form">
                <input type="hidden" id="app-id">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label for="app-name" class="block text-sm font-medium text-neutral-700 mb-1">应用名称 <span class="text-danger">*</span></label>
                        <input type="text" id="app-name" class="form-input" placeholder="请输入应用名称">
                    </div>
                    <div>
                        <label for="app-category" class="block text-sm font-medium text-neutral-700 mb-1">应用分类 <span class="text-danger">*</span></label>
                        <div class="relative">
                            <select id="app-category" class="form-input appearance-none">
                                <option value="">请选择分类</option>
                                <option value="project">项目管理</option>
                                <option value="design">设计工具</option>
                                <option value="cost">造价算量</option>
                                <option value="safety">安全管理</option>
                                <option value="document">文档管理</option>
                            </select>
                            <i class="fa fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400 pointer-events-none"></i>
                        </div>
                    </div>
                </div>

                <div class="mb-4">
                    <label for="app-description" class="block text-sm font-medium text-neutral-700 mb-1">应用描述 <span class="text-danger">*</span></label>
                    <textarea id="app-description" rows="4" class="form-input" placeholder="请输入应用描述"></textarea>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label for="app-developer" class="block text-sm font-medium text-neutral-700 mb-1">开发者</label>
                        <input type="text" id="app-developer" class="form-input" placeholder="请输入开发者名称">
                    </div>
                    <div>
                        <label for="app-version" class="block text-sm font-medium text-neutral-700 mb-1">版本号</label>
                        <input type="text" id="app-version" class="form-input" placeholder="例如：1.0.0">
                    </div>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-neutral-700 mb-1">应用图标</label>
                    <div class="flex items-center">
                        <div class="w-20 h-20 border-2 border-dashed border-neutral-300 rounded-md flex items-center justify-center mr-4">
                            <img id="app-icon-preview" src="https://picsum.photos/id/20/200/200" alt="应用图标预览" class="w-full h-full object-cover hidden">
                            <i class="fa fa-cloud-upload text-neutral-400" id="app-icon-placeholder"></i>
                        </div>
                        <div>
                            <button type="button" class="btn-secondary">
                                <i class="fa fa-upload mr-1"></i> 选择图片
                            </button>
                            <p class="text-xs text-neutral-500 mt-1">支持JPG、PNG格式，建议尺寸200x200px</p>
                        </div>
                    </div>
                </div>

                <div class="mb-4">
                    <label for="app-status" class="block text-sm font-medium text-neutral-700 mb-1">状态</label>
                    <div class="flex space-x-4">
                        <label class="inline-flex items-center">
                            <input type="radio" name="app-status" value="pending" class="text-primary focus:ring-primary" checked>
                            <span class="ml-2 text-sm text-neutral-700">审核中</span>
                        </label>
                        <label class="inline-flex items-center">
                            <input type="radio" name="app-status" value="published" class="text-primary focus:ring-primary">
                            <span class="ml-2 text-sm text-neutral-700">已上架</span>
                        </label>
                        <label class="inline-flex items-center">
                            <input type="radio" name="app-status" value="unpublished" class="text-primary focus:ring-primary">
                            <span class="ml-2 text-sm text-neutral-700">已下架</span>
                        </label>
                    </div>
                </div>
            </form>
        </div>
        <div class="p-5 border-t border-neutral-200 flex justify-end space-x-3">
            <button id="cancel-app-modal" class="btn-secondary">取消</button>
            <button id="save-app" class="btn-primary">保存</button>
        </div>
    </div>
</div>

<!-- 确认操作的模态框 - 默认隐藏 -->
<div id="confirm-modal" class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center">
    <div class="bg-white rounded-xl w-full max-w-md">
        <div class="p-5 border-b border-neutral-200">
            <h3 class="text-lg font-semibold text-neutral-800">确认操作</h3>
        </div>
        <div class="p-5">
            <p class="text-neutral-700" id="confirm-message">您确定要执行此操作吗？</p>
        </div>
        <div class="p-5 border-t border-neutral-200 flex justify-end space-x-3">
            <button id="cancel-confirm" class="btn-secondary">取消</button>
            <button id="confirm-action" class="btn-danger">确认</button>
        </div>
    </div>
</div>

<!-- 加载中提示 - 默认隐藏 -->
<!--<div id="loading-overlay" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">-->
<!--    <div class="bg-white p-6 rounded-lg shadow-xl flex items-center">-->
<!--        <i class="fa fa-spinner fa-spin text-primary text-2xl mr-3"></i>-->
<!--        <span>加载中，请稍候...</span>-->
<!--    </div>-->
<!--</div>-->

<!-- JavaScript 功能实现 -->
<script>
    // ==============================================
    // Token 管理工具类 - 与前台保持一致的认证机制
    // ==============================================

    const TokenManager = {
        // Token存储的键名
        TOKEN_KEY: 'zhizhu_app_store_token',
        // Token过期时间存储的键名
        EXPIRY_KEY: 'token_expiry',

        /**
         * 保存token到本地存储
         * @param {string} token - 后端返回的token字符串
         * @param {number} expiresIn - 有效期（秒），通常从后端获取
         */
        saveToken: function(token, expiresIn) {
            const expiryTime = new Date().getTime() + (expiresIn * 1000);
            localStorage.setItem(this.TOKEN_KEY, token);
            localStorage.setItem(this.EXPIRY_KEY, expiryTime.toString());
            console.log('Token已保存，有效期至:', new Date(expiryTime).toLocaleString());
        },

        /**
         * 从本地存储获取token
         * @returns {string|null} - 返回token或null
         */
        getToken: function() {
            if (!this.isTokenValid()) {
                this.removeToken();
                return null;
            }
            return localStorage.getItem(this.TOKEN_KEY);
        },

        /**
         * 检查token是否有效（存在且未过期）
         * @returns {boolean} - 是否有效
         */
        isTokenValid: function() {
            const token = localStorage.getItem(this.TOKEN_KEY);
            // const expiryTime = localStorage.getItem(this.EXPIRY_KEY);

            if (!token) {
                return false;
            }

            const currentTime = new Date().getTime();
            return currentTime < parseInt(expiryTime);
        },

        /**
         * 从本地存储删除token
         */
        removeToken: function() {
            localStorage.removeItem(this.TOKEN_KEY);
            localStorage.removeItem(this.EXPIRY_KEY);
            console.log('Token已删除');
        }
    };

    // ==============================================
    // 认证相关函数
    // ==============================================

    /**
     * 检查用户是否已登录（token是否有效）
     * 如果未登录，跳转到登录页
     */
    function checkLoginStatus() {
        showLoading();

        if (!TokenManager.isTokenValid()) {
            console.log('未检测到有效登录状态，跳转到登录页');
            hideLoading();
            // 跳转到登录页，记录当前页面地址以便登录后返回
            window.location.href = `/temp/login?redirect=${encodeURIComponent(window.location.href)}`;
            return false;
        }

        console.log('登录状态有效');
        return true;
    }

    /**
     * 处理退出登录
     */
    function handleLogout() {
        if (confirm('确定要退出登录吗？')) {
            showLoading();
            // 调用后端退出登录接口
            fetchLogout()
                .then(() => {
                    TokenManager.removeToken();
                    window.location.href = '/temp/login';
                })
                .catch(error => {
                    console.error('退出登录失败:', error);
                    TokenManager.removeToken();
                    window.location.href = '/temp/login';
                });
        }
    }

    // ==============================================
    // API调用工具函数 - 所有请求都会自动带上token
    // ==============================================

    /**
     * 带认证的API请求工具函数
     * 自动添加Authorization头，处理401错误
     * @param {string} url - 请求地址
     * @param {Object} options - fetch选项
     * @returns {Promise} - 返回Promise对象
     */
    function authenticatedFetch(url, options = {}) {
        const token = TokenManager.getToken();

        if (!token) {
            return Promise.reject(new Error('未登录或登录已过期'));
        }

        const headers = {
            'Content-Type': 'application/json',
            ...options.headers
        };

        headers['Authorization'] = `Bearer ${token}`;

        const fetchOptions = {
            ...options,
            headers
        };

        return fetch(url, fetchOptions)
            .then(response => {
                // 处理401未授权错误
                if (response.status === 401) {
                    TokenManager.removeToken();
                    window.location.href = `/temp/login?redirect=${encodeURIComponent(window.location.href)}`;
                    return Promise.reject(new Error('登录已过期，请重新登录'));
                }

                if (!response.ok) {
                    return response.json()
                        .then(data => {
                            throw new Error(data.message || `请求失败: ${response.status}`);
                        })
                        .catch(() => {
                            throw new Error(`请求失败: ${response.status}`);
                        });
                }

                return response.json();
            });
    }

    // ==============================================
    // 后端接口调用 - 已集成token认证
    // ==============================================

    /**
     * 获取统计数据
     */
    function fetchDashboardStats() {
        console.log('获取仪表盘统计数据');

        // 后端API地址 - 请替换为您的实际接口地址
        const apiUrl = '/api/admin/stats';

        return authenticatedFetch(apiUrl)
            .then(stats => {
                console.log('成功获取统计数据:', stats);
                updateStatsUI(stats);
                return stats;
            });
    }

    /**
     * 获取应用列表
     * @param {number} page - 页码
     * @param {number} pageSize - 每页数量
     */
    function fetchApps(page = 1, pageSize = 10) {
        console.log('获取应用列表，页码:', page);

        // 后端API地址 - 请替换为您的实际接口地址
        const apiUrl = `/api/admin/apps?page=${page}&pageSize=${pageSize}`;

        return authenticatedFetch(apiUrl);
    }

    /**
     * 获取用户列表
     * @param {number} page - 页码
     * @param {number} pageSize - 每页数量
     */
    function fetchUsers(page = 1, pageSize = 10) {
        console.log('获取用户列表，页码:', page);

        // 后端API地址 - 请替换为您的实际接口地址
        const apiUrl = `/api/admin/users?page=${page}&pageSize=${pageSize}`;

        return authenticatedFetch(apiUrl);
    }

    /**
     * 获取应用详情
     * @param {string} appId - 应用ID
     */
    function fetchAppDetail(appId) {
        console.log('获取应用详情，ID:', appId);

        // 后端API地址 - 请替换为您的实际接口地址
        const apiUrl = `/api/admin/apps/${appId}`;

        return authenticatedFetch(apiUrl);
    }

    /**
     * 保存应用信息（新增或编辑）
     * @param {Object} appData - 应用数据
     */
    function saveApp(appData) {
        console.log('保存应用信息:', appData);

        // 后端API地址 - 请替换为您的实际接口地址
        let apiUrl = '/api/admin/apps';
        let method = 'POST';

        // 如果有ID，则是编辑操作
        if (appData.id) {
            apiUrl = `/api/admin/apps/${appData.id}`;
            method = 'PUT';
        }

        return authenticatedFetch(apiUrl, {
            method: method,
            body: JSON.stringify(appData)
        });
    }

    /**
     * 删除或下架应用
     * @param {string} appId - 应用ID
     */
    function deleteOrUnpublishApp(appId) {
        console.log('下架/删除应用，ID:', appId);

        // 后端API地址 - 请替换为您的实际接口地址
        const apiUrl = `/api/admin/apps/${appId}/status`;

        return authenticatedFetch(apiUrl, {
            method: 'PATCH',
            body: JSON.stringify({ status: 'unpublished' })
        });
    }

    /**
     * 禁用用户
     * @param {string} userId - 用户ID
     */
    function blockUser(userId) {
        console.log('禁用用户，ID:', userId);

        // 后端API地址 - 请替换为您的实际接口地址
        const apiUrl = `/api/admin/users/${userId}/status`;

        return authenticatedFetch(apiUrl, {
            method: 'PATCH',
            body: JSON.stringify({ status: 'blocked' })
        });
    }

    /**
     * 获取通知列表
     */
    function fetchNotifications() {
        console.log('获取通知列表');

        // 后端API地址 - 请替换为您的实际接口地址
        const apiUrl = '/api/admin/notifications';

        return authenticatedFetch(apiUrl)
            .then(notifications => {
                console.log('成功获取通知列表:', notifications);
                const unreadCount = notifications.filter(notification => !notification.read).length;
                document.getElementById('notification-count').textContent = unreadCount;
                return notifications;
            });
    }

    /**
     * 获取当前管理员信息
     */
    function fetchAdminInfo() {
        console.log('获取管理员信息');

        // 后端API地址 - 请替换为您的实际接口地址
        const apiUrl = '/api/admin/current';

        return authenticatedFetch(apiUrl)
            .then(admin => {
                console.log('成功获取管理员信息:', admin);
                document.getElementById('admin-name').textContent = admin.name || '管理员';
                return admin;
            });
    }

    /**
     * 退出登录接口调用
     */
    function fetchLogout() {
        // 后端API地址 - 请替换为您的实际接口地址
        const apiUrl = '/api/admin/logout';

        return authenticatedFetch(apiUrl, {
            method: 'POST'
        });
    }

    // ==============================================
    // 页面初始化和事件绑定
    // ==============================================

    // 页面加载完成后执行初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 检查登录状态，如果未登录会自动跳转
        if (!checkLoginStatus()) {
            return; // 如果未登录，不再执行后续初始化
        }

        // 初始化页面功能
        initPageFunctions();

        // 加载数据
        loadDashboardData();
    });

    /**
     * 初始化页面功能
     */
    function initPageFunctions() {
        // 显示当前日期
        displayCurrentDate();

        // 初始化移动端菜单
        initMobileMenu();

        // 初始化用户菜单
        initUserMenu();

        // 初始化模态框功能
        initModals();

        // 初始化应用操作按钮
        initAppActionButtons();

        // 初始化用户操作按钮
        initUserActionButtons();

        // 初始化图表
        initCharts();
    }

    /**
     * 加载仪表盘数据
     */
    function loadDashboardData() {
        showLoading();

        // 并行加载各项数据
        Promise.all([
            fetchDashboardStats(),
            fetchNotifications(),
            fetchAdminInfo(),
            fetchApps(),
            fetchUsers()
        ])
            .then(results => {
                console.log('所有数据加载完成');
            })
            .catch(error => {
                console.error('数据加载失败:', error);
                showErrorNotification('数据加载失败，请刷新页面重试');
            })
            .finally(() => {
                hideLoading();
            });
    }

    // ==============================================
    // 页面功能实现
    // ==============================================

    /**
     * 显示当前日期
     */
    function displayCurrentDate() {
        const now = new Date();
        const options = {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            weekday: 'long'
        };
        const formattedDate = now.toLocaleDateString('zh-CN', options);
        document.getElementById('current-date').textContent = formattedDate;
    }

    /**
     * 初始化移动端菜单
     */
    function initMobileMenu() {
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        const sidebar = document.getElementById('sidebar');

        mobileMenuButton.addEventListener('click', function() {
            sidebar.classList.toggle('hidden');
            sidebar.classList.toggle('fixed');
            sidebar.classList.toggle('inset-0');
            sidebar.classList.toggle('z-40');
        });

        // 点击外部关闭侧边栏
        document.addEventListener('click', function(event) {
            if (window.innerWidth < 768 &&
                !sidebar.classList.contains('hidden') &&
                !sidebar.contains(event.target) &&
                event.target !== mobileMenuButton) {
                sidebar.classList.add('hidden');
                sidebar.classList.remove('fixed', 'inset-0', 'z-40');
            }
        });
    }

    /**
     * 初始化用户菜单
     */
    function initUserMenu() {
        const userMenuButton = document.getElementById('user-menu-button');
        const userDropdownMenu = document.getElementById('user-dropdown-menu');
        const logoutButton = document.getElementById('logout-button');

        // 切换用户菜单显示/隐藏
        userMenuButton.addEventListener('click', function(e) {
            e.stopPropagation();
            userDropdownMenu.classList.toggle('hidden');
        });

        // 点击外部关闭用户菜单
        document.addEventListener('click', function() {
            userDropdownMenu.classList.add('hidden');
        });

        // 阻止菜单内部点击事件冒泡
        userDropdownMenu.addEventListener('click', function(e) {
            e.stopPropagation();
        });

        // 绑定退出登录事件
        logoutButton.addEventListener('click', handleLogout);
    }

    /**
     * 初始化模态框功能
     */
    function initModals() {
        const appModal = document.getElementById('app-modal');
        const closeAppModal = document.getElementById('close-app-modal');
        const cancelAppModal = document.getElementById('cancel-app-modal');
        const saveAppBtn = document.getElementById('save-app');
        const confirmModal = document.getElementById('confirm-modal');
        const cancelConfirm = document.getElementById('cancel-confirm');
        const confirmAction = document.getElementById('confirm-action');

        // 关闭应用模态框
        function closeModal() {
            appModal.classList.add('hidden');
            appModal.classList.remove('flex');
            confirmModal.classList.add('hidden');
            confirmModal.classList.remove('flex');
        }

        closeAppModal.addEventListener('click', closeModal);
        cancelAppModal.addEventListener('click', closeModal);
        cancelConfirm.addEventListener('click', closeModal);

        // 点击模态框外部关闭
        appModal.addEventListener('click', function(e) {
            if (e.target === appModal) {
                closeModal();
            }
        });

        confirmModal.addEventListener('click', function(e) {
            if (e.target === confirmModal) {
                closeModal();
            }
        });

        // 保存应用信息
        saveAppBtn.addEventListener('click', function() {
            saveAppFormData();
        });

        // 确认操作
        confirmAction.addEventListener('click', function() {
            executeConfirmedAction();
        });
    }

    /**
     * 初始化应用操作按钮
     */
    function initAppActionButtons() {
        // 编辑应用按钮
        document.querySelectorAll('.app-edit-btn').forEach(button => {
            button.addEventListener('click', function() {
                const appId = this.getAttribute('data-app-id');
                openEditAppModal(appId);
            });
        });

        // 删除/下架应用按钮
        document.querySelectorAll('.app-delete-btn').forEach(button => {
            button.addEventListener('click', function() {
                const appId = this.getAttribute('data-app-id');
                const actionText = this.textContent.trim(); // "下架"或"删除"

                openConfirmModal(
                    `您确定要${actionText}此应用吗？`,
                    'app',
                    appId
                );
            });
        });
    }

    /**
     * 初始化用户操作按钮
     */
    function initUserActionButtons() {
        // 编辑用户按钮
        document.querySelectorAll('.user-edit-btn').forEach(button => {
            button.addEventListener('click', function() {
                const userId = this.getAttribute('data-user-id');
                // 这里可以实现打开用户编辑模态框的逻辑
                alert(`准备编辑用户: ${userId}`);
            });
        });

        // 禁用用户按钮
        document.querySelectorAll('.user-block-btn').forEach(button => {
            if (!button.classList.contains('cursor-not-allowed')) {
                button.addEventListener('click', function() {
                    const userId = this.getAttribute('data-user-id');

                    openConfirmModal(
                        '您确定要禁用此用户吗？禁用后该用户将无法登录系统。',
                        'user',
                        userId
                    );
                });
            }
        });
    }

    /**
     * 初始化图表
     */
    function initCharts() {
        // 下载趋势图表
        const downloadsCtx = document.getElementById('downloads-chart').getContext('2d');
        new Chart(downloadsCtx, {
            type: 'line',
            data: {
                labels: ['1日', '2日', '3日', '4日', '5日', '6日', '7日'],
                datasets: [{
                    label: '下载量',
                    data: [120, 190, 150, 280, 220, 350, 320],
                    borderColor: '#0a3d62',
                    backgroundColor: 'rgba(10, 61, 98, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });

        // 应用分类占比图表
        const categoriesCtx = document.getElementById('categories-chart').getContext('2d');
        new Chart(categoriesCtx, {
            type: 'doughnut',
            data: {
                labels: ['项目管理', '设计工具', '造价算量', '安全管理', '文档管理'],
                datasets: [{
                    data: [32, 24, 18, 15, 11],
                    backgroundColor: [
                        '#0a3d62',
                        '#60a3bc',
                        '#27ae60',
                        '#f39c12',
                        '#e74c3c'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                cutout: '70%'
            }
        });
    }

    // ==============================================
    // 模态框操作函数
    // ==============================================

    /**
     * 打开编辑应用模态框
     * @param {string} appId - 应用ID，为空则是新增
     */
    function openEditAppModal(appId) {
        const appModal = document.getElementById('app-modal');
        const modalTitle = document.getElementById('app-modal-title');
        const appIdInput = document.getElementById('app-id');

        // 重置表单
        document.getElementById('app-form').reset();
        document.getElementById('app-icon-preview').classList.add('hidden');
        document.getElementById('app-icon-placeholder').classList.remove('hidden');

        if (appId) {
            // 编辑已有应用
            modalTitle.textContent = '编辑应用';
            appIdInput.value = appId;

            showLoading();
            // 获取应用详情并填充表单
            fetchAppDetail(appId)
                .then(app => {
                    // 填充表单数据
                    document.getElementById('app-name').value = app.name || '';
                    document.getElementById('app-category').value = app.category || '';
                    document.getElementById('app-description').value = app.description || '';
                    document.getElementById('app-developer').value = app.developer || '';
                    document.getElementById('app-version').value = app.version || '';

                    // 显示应用图标
                    if (app.iconUrl) {
                        document.getElementById('app-icon-preview').src = app.iconUrl;
                        document.getElementById('app-icon-preview').classList.remove('hidden');
                        document.getElementById('app-icon-placeholder').classList.add('hidden');
                    }

                    // 设置状态单选按钮
                    const statusRadios = document.querySelectorAll('input[name="app-status"]');
                    statusRadios.forEach(radio => {
                        if (radio.value === app.status) {
                            radio.checked = true;
                        }
                    });

                    // 显示模态框
                    appModal.classList.remove('hidden');
                    appModal.classList.add('flex');
                })
                .catch(error => {
                    console.error('获取应用详情失败:', error);
                    showErrorNotification('加载应用详情失败');
                })
                .finally(() => {
                    hideLoading();
                });
        } else {
            // 新增应用
            modalTitle.textContent = '添加新应用';
            appIdInput.value = '';
            appModal.classList.remove('hidden');
            appModal.classList.add('flex');
        }
    }

    /**
     * 打开确认操作模态框
     * @param {string} message - 确认消息
     * @param {string} type - 操作类型：'app' 或 'user'
     * @param {string} id - 操作对象ID
     */
    function openConfirmModal(message, type, id) {
        const confirmModal = document.getElementById('confirm-modal');
        const confirmMessage = document.getElementById('confirm-message');

        // 设置确认消息
        confirmMessage.textContent = message;

        // 存储要操作的对象信息
        confirmModal.setAttribute('data-type', type);
        confirmModal.setAttribute('data-id', id);

        // 显示模态框
        confirmModal.classList.remove('hidden');
        confirmModal.classList.add('flex');
    }

    /**
     * 执行确认的操作
     */
    function executeConfirmedAction() {
        const confirmModal = document.getElementById('confirm-modal');
        const type = confirmModal.getAttribute('data-type');
        const id = confirmModal.getAttribute('data-id');

        showLoading();

        if (type === 'app') {
            // 处理应用下架/删除
            deleteOrUnpublishApp(id)
                .then(result => {
                    console.log('应用操作成功:', result);
                    showSuccessNotification('操作成功');
                    // 重新加载数据
                    loadDashboardData();
                })
                .catch(error => {
                    console.error('应用操作失败:', error);
                    showErrorNotification('操作失败，请重试');
                })
                .finally(() => {
                    hideLoading();
                    confirmModal.classList.add('hidden');
                    confirmModal.classList.remove('flex');
                });
        } else if (type === 'user') {
            // 处理用户禁用
            blockUser(id)
                .then(result => {
                    console.log('用户操作成功:', result);
                    showSuccessNotification('操作成功');
                    // 重新加载数据
                    loadDashboardData();
                })
                .catch(error => {
                    console.error('用户操作失败:', error);
                    showErrorNotification('操作失败，请重试');
                })
                .finally(() => {
                    hideLoading();
                    confirmModal.classList.add('hidden');
                    confirmModal.classList.remove('flex');
                });
        }
    }

    /**
     * 保存应用表单数据
     */
    function saveAppFormData() {
        // 收集表单数据
        const appData = {
            id: document.getElementById('app-id').value || null,
            name: document.getElementById('app-name').value.trim(),
            category: document.getElementById('app-category').value,
            description: document.getElementById('app-description').value.trim(),
            developer: document.getElementById('app-developer').value.trim(),
            version: document.getElementById('app-version').value.trim(),
            status: document.querySelector('input[name="app-status"]:checked').value
        };

        // 简单验证
        if (!appData.name) {
            showErrorNotification('请输入应用名称');
            return;
        }

        if (!appData.category) {
            showErrorNotification('请选择应用分类');
            return;
        }

        if (!appData.description) {
            showErrorNotification('请输入应用描述');
            return;
        }

        showLoading();

        // 保存应用数据
        saveApp(appData)
            .then(result => {
                console.log('应用保存成功:', result);
                showSuccessNotification(appData.id ? '应用更新成功' : '应用添加成功');

                // 关闭模态框并重新加载数据
                const appModal = document.getElementById('app-modal');
                appModal.classList.add('hidden');
                appModal.classList.remove('flex');

                loadDashboardData();
            })
            .catch(error => {
                console.error('应用保存失败:', error);
                showErrorNotification('保存失败，请重试');
            })
            .finally(() => {
                hideLoading();
            });
    }

    // ==============================================
    // 页面更新函数
    // ==============================================

    /**
     * 更新统计数据UI
     * @param {Object} stats - 统计数据对象
     */
    function updateStatsUI(stats) {
        if (!stats) return;

        // 更新统计数字
        document.getElementById('total-apps').textContent = stats.totalApps || '0';
        document.getElementById('total-users').textContent = formatNumber(stats.totalUsers || 0);
        document.getElementById('total-downloads').textContent = formatNumber(stats.totalDownloads || 0);
        document.getElementById('active-users').textContent = formatNumber(stats.activeUsers || 0);
        document.getElementById('pending-apps').textContent = stats.pendingApps || '0';
        document.getElementById('new-users-today').textContent = stats.newUsersToday || '0';
    }

    // ==============================================
    // 工具函数
    // ==============================================

    /**
     * 格式化数字（添加千位分隔符）
     * @param {number} num - 要格式化的数字
     * @returns {string} 格式化后的数字字符串
     */
    function formatNumber(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    /**
     * 显示加载状态
     */
    function showLoading() {
        document.getElementById('loading-overlay').classList.remove('hidden');
    }

    /**
     * 隐藏加载状态
     */
    function hideLoading() {
        document.getElementById('loading-overlay').classList.add('hidden');
    }

    /**
     * 显示错误通知
     * @param {string} message - 错误信息
     */
    function showErrorNotification(message) {
        alert(`错误: ${message}`);
    }

    /**
     * 显示成功通知
     * @param {string} message - 成功信息
     */
    function showSuccessNotification(message) {
        alert(`成功: ${message}`);
    }
</script>
</body>
</html>
